#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.articleController import ArticleController


import datetime
import math

from flask import current_app, jsonify
from sqlalchemy import or_,and_
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from models.article import Article
from models.user import User
from models.administrator import Administrator
from utils import commons
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN
from utils.rsa_encryption_decryption import RSAEncryptionDecryption

class ArticleService(ArticleController):

    @classmethod
    def add_article(cls, article_title, article_content, user_id):
        try:
            new_article = Article(
                article_id=GenerateID.create_random_id(),
                article_title=article_title,
                article_content=article_content,
                user_id=user_id,
                status=0,  # 假设0表示未审核状态
                is_delete=0
            )
            db.session.add(new_article)
            db.session.commit()

            data_dict = {
                'article_id': new_article.article_id,
                'article_title': new_article.article_title,
                'create_time': new_article.create_time,
            }
            return {'code': RET.OK, 'message': '文章上传成功', 'data': data_dict}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，文章上传失败', 'data': str(e)}

        finally:
            db.session.close()

    # 获取已审核通过文章列表
    @classmethod
    def get_approved_articles(cls):
        try:
            articles = Article.query.filter_by(status=1, is_delete=0).all()  # 获取已审核且未删除的文章
            articles_list = []
            for article in articles:
                article_dict = {
                    'article_id': article.article_id,
                    'article_title': article.article_title,
                    'article_content': article.article_content,
                    'user_id': article.user_id,
                    'administrator_id': article.administrator_id,
                    'status': article.status,
                    'isDelete': article.is_delete,
                    'create_time': article.create_time,
                    'update_time': article.update_time
                }
                articles_list.append(article_dict)
            return {'code': RET.OK, 'message': '获取文章列表成功', 'data': articles_list}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取文章列表失败', 'data': str(e)}


    # 获取未审核通过文章列表
    @classmethod
    def get_disapproved_articles(cls):
        try:
            articles = Article.query.filter_by(status=0, is_delete=0).all()  # 获取已审核且未删除的文章
            articles_list = []
            for article in articles:
                article_dict = {
                    'article_id': article.article_id,
                    'article_title': article.article_title,
                    'article_content': article.article_content,
                    'user_id': article.user_id,
                    'administrator_id': article.administrator_id,
                    'status': article.status,
                    'isDelete': article.is_delete,
                    'create_time': article.create_time,
                    'update_time': article.update_time
                }
                articles_list.append(article_dict)
            return {'code': RET.OK, 'message': '获取文章列表成功', 'data': articles_list}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取文章列表失败', 'data': str(e)}


    # 管理员审核文章
    @classmethod
    def approve_article(cls, article_id, administrator_id):
        try:
            article = Article.query.filter_by(article_id=article_id, is_delete=0).first()
            if not article:
                return {'code': RET.NODATA, 'message': '文章不存在或已被删除', 'data': None}

            if article.status != 0:
                return {'code': RET.PARAMERR, 'message': '文章已审核或状态异常', 'data': None}

            article.status = 1  # 设置为已审核状态
            article.administrator_id = administrator_id
            article.update_time = datetime.datetime.now()

            db.session.commit()

            data_dict = {
                'article_id': article.article_id,
                'article_title': article.article_title,
                'status': article.status,
                'administrator_id': article.administrator_id,
                'update_time': article.update_time
            }
            return {'code': RET.OK, 'message': '文章审核通过', 'data': data_dict}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，文章审核失败', 'data': str(e)}

        finally:
            db.session.close()



    # 管理员审核文章
    @classmethod
    def delete_article(cls, article_id, administrator_id):
        try:
            article = Article.query.filter_by(article_id=article_id, is_delete=0).first()
            if not article:
                return {'code': RET.NODATA, 'message': '文章不存在或已被删除', 'data': None}

            article.is_delete = 1  # 设置为已是删除状态
            article.administrator_id = administrator_id
            article.update_time = datetime.datetime.now()

            db.session.commit()

            data_dict = {
                'article_id': article.article_id,
                'article_title': article.article_title,
                'status': article.status,
                'administrator_id': article.administrator_id,
                'update_time': article.update_time
            }
            return {'code': RET.OK, 'message': '文章已删除', 'data': data_dict}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，文章删除失败', 'data': str(e)}

        finally:
            db.session.close()

